package com.binance.notification.web.service.abnormaltrade.sharding;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.binance.notification.web.service.abnormaltrade.integration.ExchangeProductService;
import com.binance.notification.web.service.abnormaltrade.log.LoggerUtils;
import com.binance.notification.web.service.abnormaltrade.sharding.models.ShardingInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * 对不同的业务进行分片的服务
 */
@Service
public class JobShardingService {
    private static final org.slf4j.Logger logger = LoggerUtils.getLogger(JobShardingService.class);
    @Autowired
    private ExchangeProductService exchangeProductService;

    /**
     * symbol 只支持BTC USDT
     * 
     * @throws Exception
     */
    public Set<String> getShardingSymbolSet(int index, int total, String symbol) throws Exception {
        List<String> symbols = Lists.newArrayList();
        if (StringUtils.isBlank(symbol)) {
            symbols = exchangeProductService.getUsdtAndBtcSymbolList();
        } else {
            symbols = exchangeProductService.getSymbolListForDefinedCoin(symbol);
        }
        if (CollectionUtils.isEmpty(symbols)) {
            logger.info("JobShardingService.getKLineShardingSymbolSet:symbols is empty");
            return Sets.newHashSet();
        }
        ShardingInfo shardingInfo = getShardingInfo(index, total, symbols.size());
        logger.info(
                "JobShardingService.getKLineShardingSymbolSet : shardingNum={},startIndex={},endIndex={},symbolSize={}",
                shardingInfo.getShardingNum(), shardingInfo.getStartIndex(), shardingInfo.getEndIndex(),
                symbols.size());
        List<String> subList = Lists.newArrayList();
        subList.addAll(symbols.subList(shardingInfo.getStartIndex(), shardingInfo.getEndIndex()));
        Set<String> subSymbolSet = new HashSet<>(subList);
        logger.info("JobShardingService.getKLineShardingSymbolSet : subSymbolSet={}", subSymbolSet.size());
        return subSymbolSet;
    }

    private ShardingInfo getShardingInfo(int index, int total, int collectionSize) {
        int shardingNum = collectionSize / total;// list的大小处于分片数等于，每台机器执行多少
        int startIndex = index * shardingNum;
        int endIndex = (index + 1) * shardingNum;
        if (total == (index + 1) && endIndex < collectionSize) {
            endIndex = collectionSize;
        }
        ShardingInfo shardingInfo = new ShardingInfo();
        shardingInfo.setShardingNum(shardingNum);
        shardingInfo.setStartIndex(startIndex);
        shardingInfo.setEndIndex(endIndex);
        return shardingInfo;
    }
}
